package com.springboot.springmvc01helloworld.controller;

import com.springboot.springmvc01helloworld.bean.Person;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;

@RestController

public class ResponseTestController {
    //resp01：实验1：返回json数据
    Person person = new Person();
    @RequestMapping("/resp01")
    public Person resp01(){

        person.setUsername("张三");
        person.setPassword("123456");
        person.setCellphone("123456789");
        person.setAgreement(true);
        person.setSex("男");
        person.setHobbies(new String[]{"篮球","足球"});
        return person;
    }

    //resp02：实验2：文件下载
    @RequestMapping("/resp02")
    public ResponseEntity<byte[]> download() throws IOException {

        FileInputStream inputStream = new FileInputStream("D:\\img\\1.jpg");

        //问题1：使用中文名时会乱码，修改如下
        String encode = URLEncoder.encode("哈哈哈.jpg","UTF-8");

        //问题2：内存溢出
        InputStreamResource inputStreamResource = new InputStreamResource(inputStream);

        byte[] bytes = inputStream.readAllBytes();


        return ResponseEntity.ok()
                //文件内容类型
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                //文件内容大小
                .contentLength(inputStream.available())//文件内容有多大，可存储的空间也多大
                //文件内容处理方式
                .header("Content-Disposition","attachment;filename=test.txt")
                .body("hello world".getBytes());
    }
}
